import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtForm, AtInput, AtButton, AtIcon} from "taro-ui"
import {View, Switch, Picker, Text} from "@tarojs/components"
import "./profile.scss"
import WxValidate from '../../utils/wx-validate'
import {vcmonitor} from "../../utils/tools";
import {user} from "../../utils/user.service"
import {http} from "../../utils/http"
import {REGION_ALL, SELLER_INFO, UPDATE_SELLER_INFO} from "../../constants/api"
import {SellerInfo, PlatformSet} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";

interface stateType {
  addressData: any
  formData: formData
  errList: {
    is_show_phone?: boolean
    real_name: boolean
    poster_name?: boolean
    phone?: boolean
    slogan?: boolean
    company?: boolean
    area?: boolean
    address?: boolean
    wx_no?: boolean
  }
  sellerInfo: SellerInfo | false
  submiting: boolean
  rate: number
}

interface updateInfo {
  id: number
  poster_name: string
  real_name: string
  phone: string
  slogan: string
  company: string
  area: string
  address: string
  delivery_province: string
  delivery_city: string
  delivery_area: string
  is_show_phone: number
  wx_no?: string
  rate?: number
}

interface formData {
  is_show_phone: boolean
  real_name: string
  poster_name: string
  phone: string
  slogan: string
  company: string
  area: string[]
  wx_no?: string
  address: string
}

export default class Profile extends Component {
  state: stateType = {
    addressData: [],
    formData: {
      is_show_phone: true,
      real_name: '',
      poster_name: '',
      phone: '',
      slogan: '',
      company: '',
      area: ["北京市", "北京市", "西城区"],
      address: ''
    },
    rangeKey: [0, 0, 0],
    rangeData: [[], [], []],
    errList: {
      real_name: false
    },
    sellerInfo: false,
    submiting: false,
    rate: 0
  }
  rules = {
    poster_name: {
      required: true,
    },
    phone: {
      tel: true
    }
  }
  message = {
    poster_name: {
      required: "昵称不能为空",
    },
    phone: {
      tel: "手机号码不正确"
    }
  }
  platformSet: PlatformSet | false = false

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    this.platformSet = await platform.getSetting()
    const sellerInfo = await http.get<SellerInfo>(SELLER_INFO, {})
    if (sellerInfo) {
      const {
        is_show_phone,
        real_name,
        poster_name,
        phone,
        wx_no,
        slogan,
        company,
        delivery_province,
        delivery_city,
        delivery_area,
        address
      } = sellerInfo
      const is_show = is_show_phone === 1 ? true : false
      const formData = {
        is_show_phone: is_show,
        real_name,
        poster_name,
        phone,
        wx_no,
        slogan,
        company,
        area: [delivery_province, delivery_city, delivery_area],
        delivery_province: delivery_province,
        delivery_city: delivery_city,
        delivery_area: delivery_area,
        address
      }
      this.setState({sellerInfo, formData, rate: Math.floor(sellerInfo.rate * 100)})
    }
    if (process.env.TARO_ENV === 'h5') {
      const data = await http.carGet(REGION_ALL)
      this.setState({addressData: data}, async () => {
        this.handleCityData([0, 0, 0]);
      })
    }
  }

  inputChange(type, value) {
    const oldData = this.state.formData
    if (type == 'slogan') {
      if (value.length > 20) {
        Taro.showToast({title: '广告语最多20个字奥！', icon: 'none'})
        value = value.substring(0, 20)
      }
    }
    oldData[type] = value
    this.setState({formData: oldData})
  }

  regionChange(e) {
    const oldData = this.state.formData
    oldData['area'] = e.detail.value
    this.setState({formData: oldData})
  }

  phoneSwitch(e) {
    if (e.detail.value) {
      Taro.showToast({title: '开启电话在' + process.env.fxName + '海报上展示', icon: 'none'})
    } else {
      Taro.showToast({title: '关闭电话在' + process.env.fxName + '海报上展示', icon: 'none'})
    }
    const formData = this.state.formData
    formData.is_show_phone = e.detail.value
    this.setState({formData})
  }

  handleCityData = key => {
    const {addressData} = this.state
    // 处理数据。
    const provinceList = []; // 省
    const cityList = []; // 市
    const areaList = []; // 区
    for (let i = 0; i < addressData.length; i++) {
      // 获取省
      const province = addressData[i];
      provinceList.push(province.name);
    }
    if (addressData[key[0]].areaList && addressData[key[0]].areaList.length > 0) {
      for (let i = 0; i < addressData[key[0]].areaList.length; i++) {
        // 获取对应省下面的市
        const city = addressData[key[0]].areaList[i];
        cityList.push(city.name);
      }
    }
    for (
      let i = 0;
      i < addressData[key[0]].areaList[key[1]].areaList.length;
      i++
    ) {
      // 获取市下面对应区
      const country = addressData[key[0]].areaList[key[1]].areaList[i].name;
      areaList.push(country);
    }
    // }
    const newRange = [];
    newRange.push(provinceList);
    newRange.push(cityList);
    newRange.push(areaList);
    this.setState({
      rangeData: newRange, // 省市区所有的数据
      rangeKey: key // key是多列选择器需要展示的下标，因为是初始化，所以我们传入[0,0,0]
    });
  };

  async submitForm() {
    this.setState({submiting: true}, async () => {
      const validate = new WxValidate(this.rules, this.message)
      if (!validate.checkForm(this.state.formData)) {
        const oldData = this.state.errList
        if (validate && validate.errorList && validate.errorList[0].param) {
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({errList: oldData, submiting: false})
        return false;
      }
      const area = this.state.formData.area
      const id = this.state.sellerInfo && this.state.sellerInfo.id || 0
      const data: updateInfo = {
        ...this.state.formData,
        is_show_phone: this.state.formData.is_show_phone ? 1 : 0,
        area: area.join(','),
        id,
        delivery_province: area[0],
        delivery_city: area[1],
        delivery_area: area[2],
      }

      if (this.state.sellerInfo && this.platformSet) {
        if (this.state.sellerInfo.type === 2 && this.platformSet.platformSellerType === 0) {
          data.rate = this.state.rate || 0
        }
      }
      const ret = await http.post(UPDATE_SELLER_INFO, data)
      if (ret) {
        Taro.showToast({title: '保存成功'})
        this.setState({submiting: false})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack()
        }, 1500)
      } else {
        this.setState({submiting: false})
      }
    })
  }

  onChange = e => {
    const {value} = e.detail;
    //console.log(e.detail)
    this.getAddressName(value);
  };
  getAddressName = value => {
    // 这里是转化用户选择的地址数据
    const {data, formData, addressData} = this.state
    formData.area = []
    if (addressData[value[0]]) {
      formData.delivery_province = addressData[value[0]].name; // 省名称
      formData.area.push(formData.delivery_province)
      if (
        addressData[value[0]].areaList &&
        addressData[value[0]].areaList[value[1]]
      ) {
        formData.delivery_city = addressData[value[0]].areaList[value[1]].name;
        formData.area.push(formData.delivery_city)
        if (
          addressData[value[0]].areaList[value[1]].areaList &&
          addressData[value[0]].areaList[value[1]].areaList[value[2]]
        ) {
          formData.delivery_area = addressData[value[0]].areaList[value[1]].areaList[value[2]].name;
          formData.area.push(formData.delivery_area)
        }
      }
    }
    this.setState({
      formData, data
    });
  };
  onColumnChange = e => {
    const {rangeKey} = this.state;
    const changeColumn = e.detail;
    const {column, value} = changeColumn;
    switch (column) { // 根据改变不同的列，来显示不同的数据
      case 0:
        this.handleCityData([value, 0, 0]);
        break;
      case 1:
        this.handleCityData([rangeKey[0], value, 0]);
        break;
      case 2:
        this.handleCityData([rangeKey[0], rangeKey[1], value]);
        break;
    }
  };

  render() {
    const {rangeData, rangeKey, formData, errList, submiting} = this.state
    return (
      <View className='profile-root'>
        <Index />
        <GzhAuth />
        <View className='head'>
          <View className='title'>{process.env.fxName}资料修改</View>
          <View className='tips'>请修改需要调整的内容</View>
        </View>
        <AtForm>
          <AtInput error={errList.poster_name} maxLength={12} onChange={this.inputChange.bind(this, 'poster_name')}
            name='poster_name' title='昵称' value={formData.poster_name} placeholder='请填写昵称（2-12字）'
          />
          <AtInput error={errList.real_name} maxLength={15} onChange={this.inputChange.bind(this, 'real_name')}
            name='real_name' title='姓名'
            value={formData.real_name && formData.real_name != 'null' ? formData.real_name : ''}
            placeholder='请填写姓名'
          />
          <AtInput error={errList.phone} onChange={this.inputChange.bind(this, 'phone')} name='phone' title='手机号码'
            value={formData.phone} placeholder='请填写手机号（无需+86）'
          >
            {this.platformSet.poster_show_phone === 1 &&
            <Switch className='switch' color={`${process.env.mainColor}`} onChange={this.phoneSwitch.bind(this)}
              checked={formData.is_show_phone}
            />}
          </AtInput>
          <AtInput error={errList.wx_no} onChange={this.inputChange.bind(this, 'wx_no')} maxLength={50} name='wx_no'
            title='微信号' value={formData.wx_no} placeholder='请填写微信号'
          />

          <AtInput error={errList.slogan} onChange={this.inputChange.bind(this, 'slogan')} maxLength={20} name='slogan'
            title='广告语' value={formData.slogan} placeholder='请填写广告语(20字以内)'
          />
          <AtInput error={errList.company} onChange={this.inputChange.bind(this, 'company')} maxLength={30}
            name='company' title='公司名称' value={formData.company} placeholder='请填写公司名称'
          />
          {process.env.TARO_ENV === "h5" ?
            <Picker
              mode='multiSelector' // 多列选择
              onChange={this.onChange} // change事件
              onColumnChange={this.onColumnChange} // 某列改变的事件
              range={rangeData} //需要展示的数据
              value={rangeKey} // 选择的下标
            >
              <View className='add-flex'>
                <View className='label'>选择城市</View>
                <View className='addcheck'>
                  {formData.delivery_province && (
                    <Text>
                      {formData.delivery_province}
                      {formData.delivery_city}
                      {formData.delivery_area}
                    </Text>
                  )}
                  {!formData.delivery_province && (
                    <Text style='color:#666'>选择省市区</Text>
                  )}
                  <AtIcon value='chevron-right' size='14' color='#888888' />
                </View>
              </View>
            </Picker>
            :
            <Picker mode='region' value={formData.area} onChange={this.regionChange.bind(this)}>
              <View className='at-input'>
                <View className='at-input__container'>
                  <View className='at-input__title'>选择城市</View>
                  <View className='at-input__input'>{formData.area.join("-")}</View>
                </View>
              </View>
            </Picker>}
          <AtInput error={errList.address} maxLength={30} onChange={this.inputChange.bind(this, 'address')}
            name='address' title='详细地址' value={formData.address} placeholder='请填写详细地址'
          />
        </AtForm>
        <View className='btn'><AtButton disabled={submiting} loading={submiting} type='primary' formType='submit'
          onClick={this.submitForm.bind(this)}
        >保存修改</AtButton></View>
        <View className='ios' />
      </View>
    )
  }
}
